<?php

/**
 * @author 	Samuel Carlier
 * @package	P3Base_Mailer
 */
class P3Base_Mailer_MessagePart {

	/**
	 * @var string
	 */
	private $_encoding;

	/**
	 * @var string
	 */
	private $_content;

	/**
	 * @param string $content
	 * @param string $encoding		
	 */
	public function __construct($content, $encoding='8bit') {
		$this->_content  = $content;
		$this->_encoding = $encoding;
	}

	/**
	 * @return string
	 */
	public function getContent() {
		return $this->_encoded();	
	}

	/**
	 * @param string $encoding
	 */
	public function setEncoding($encoding) {
		$this->_encoding = $encoding;	
	}

	/**
	 * @return string
	 */
	public function getEncoding() {
		return $this->_encoding;	
	}
		
	/**
	 * @param  string $content
	 * @return string
	 */
	private function _encoded() {
		if(empty($this->_content)) return '';

		$content = str_replace(array("\r", "\n"), P3Base_Mailer_Handler_SMTP::CRLF, $this->_content);
		
		switch($this->_encoding) {
			case P3Base_Mailer_Message::ENCODING_7BIT:
			case P3Base_Mailer_Message::ENCODING_8BIT:
				$content = $this->_bitEncoding($content);
			break;

			case P3Base_Mailer_Message::ENCODING_QUOTE:
				$content = $this->_quotedPrintable($content);
			break;

			default:
				throw new P3Base_Mailer_Exception(sprintf(P3Base_Language_Translator::get('unsupported_encoding'), $this->_encoding));
		}

		$content = str_replace("\n.", "\n..", $content);
		return $content;
	}
	
	/**
	 * format text to quoted-printable
	 * line-lenght will be 78 including CRLF
	 * 
	 * @param	string	$content
	 * @return 	string
	 */
	private function _quotedPrintable($content) {

		$fp = tmpfile();
		$write = fwrite($fp, $content, strlen($content));

		if($write === false) {
			throw new P3Base_Mailer_Exception(sprintf(P3Base_Language_Translator::get('write_file_error'), $this->_encoding));
		}

		//reset pointer
		fseek($fp, 0);

		$params = array('line-length' => 76, 'line-break-chars' => P3Base_Mailer_Handler_SMTP::CRLF);
		stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);

		$content = stream_get_contents($fp);
		fclose($fp);

		if($content === false) {
			throw new P3Base_Mailer_Exception(P3Base_Language_Translator::get('read_file_error'));
		}

		return $content;
	}
	
	/**
	 * according RFC 2822 lines cannot be longer then 1000 chars including CRLF
	 * 
	 * @param string $content
	 */
	private function _bitEncoding($content) {
		$encoded = '';
		$start	 = 0;
		$offset  = 0;

		$content = $content . P3Base_Mailer_Handler_SMTP::CRLF;
		while(($offset = strpos($content, P3Base_Mailer_Handler_SMTP::CRLF, $offset)) !== false) {
			$offset += 2;
			$limit = $offset - $start;

			$buffer = substr($content, $start, $limit);
			if($limit > 1000) {
				$buffer = wordwrap($buffer, 998, P3Base_Mailer_Handler_SMTP::CRLF, 1) . P3Base_Mailer_Handler_SMTP::CRLF;
			}

			$encoded .= $buffer;
			$start += $limit;
		}

		return rtrim($encoded);
	}
}

?>